package com.demo.datastructure.stack;

import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: ljr
 * @time: 2021/4/26 17:24
 */
public class Solution2 {

    private static final Map<Character,Character> map = new HashMap<Character,Character>(){{
        put('{','}'); put('[',']'); put('(',')'); put('?','?');
    }};

    public boolean isValid(String s) {
        Stack stack = new Stack();
        for(Character c : s.toCharArray()){
            if(map.containsKey(c)){
                stack.pop(c);
            }else{
                if(!map.get(stack.getLast()).equals(c)){
                    return false;
                }else{
                    stack.push(stack.getLast());
                }
            }

        }

        return stack.getCount() == 0;
    }

    private class Stack{
        private Character[] args = new Character[10];
        private int count;
        private int length = 10;

        public Integer getCount(){
            return count;
        }

        public Character getLast(){
            return args[length-count];
        }


        public void pop(Character symbol){
            if(++count == length){
                grow();
            }
            args[length-count] = symbol;
        }

        public boolean push(Character symbol){
            if(count == 0 || !args[length-count].equals(symbol)){
                return false;
            }
            args[length-count] = null;
            count--;
            return true;
        }


        private void grow(){
            int oldLength = length;
            Character[] newArgs = new Character[length = length*2];
            for(int i = 0; i < oldLength; i++){
                newArgs[oldLength+i] = args[i];
            }
            args = newArgs;
        }



    }
}
